package com.ebeitech.auction.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.ebeitech.auction.application.EbeiApplication;
import com.ebeitech.auction.domain.*;
import com.ebeitech.library.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by alice on 2017/10/24.
 */
public class CommonDBHelper extends DBSQLiteOpenHelper {

	/**
	 * 数据库名称
	 * userAccount + 后缀
	 */
	private static String DB_NAME = "";
	public final static String DB_NAME_SUFFIX = "_ebei";
	/**
	 * 数据库版本号
	 * 每次添加新的字段时加一
	 */
	private static final int DB_VERSION = 6;

	/**
	 * 数据库表
	 * bean 需要添加注解@Table
	 */
	private static final Class<?>[] model_Classes = {
			User.class,
			CrashInfo.class,
			ChatMessage.class
	};
	private static List<DBChangeInterface> daoManager = new ArrayList<>();
	/**
	 * 数据库实例
	 */
	private static CommonDBHelper DBHelper;
	private static Context mContext;


	public CommonDBHelper() {
		super(mContext, DB_NAME, null, DB_VERSION, model_Classes);

		//获取数据库DB 初始化数据库
		this.getWritableDatabase();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		super.onCreate(db);
	}

	public static CommonDBHelper getDBHelper(String userAccount){
		if(mContext == null){
			mContext = EbeiApplication.getContext();
		}
		if(StringUtil.isEmpty(userAccount)){
			userAccount = EbeiApplication.getUserAccount();
		}
		if(StringUtil.isEmpty(DB_NAME)){
			DB_NAME = userAccount + DB_NAME_SUFFIX;
		}
		if(mContext != null && !StringUtil.isEmpty(DB_NAME)){
			if(DBHelper == null){
				DBHelper = new CommonDBHelper();
			}else if(DBHelper != null && !DB_NAME.equals(DBHelper.getDatabaseName()) ){
				DBHelper.close();
				DBHelper = new CommonDBHelper();
			}
		}
		return DBHelper;
	}
	/**
	 * 获取数据库实例
	 * @return
	 */
	public static CommonDBHelper getDBHelper() {
		return getDBHelper(null);
	}


	/**
	 * 切换数据库
	 * @param dbName
	 */
	public static void changeDBHelper(String dbName) {
		if(DBHelper != null){
			for (DBChangeInterface dao:daoManager) {
				dao.DBChange();
			}
			DBHelper.close();
			DB_NAME = null;
			DBHelper = null;
		}
		daoManager.clear();
		getDBHelper(dbName);
	}

	public static String getDbName() {
		return DB_NAME;
	}

	public static int getDbVersion() {
		return DB_VERSION;
	}

	public static void addToDaoManager(DBChangeInterface dao){
		daoManager.add(dao);
	}

}
